﻿using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
using Urs.Core;
using Urs.Data.Domain.Users;
using Urs.Framework.Controllers;
using Urs.Plugin.Api.Models.Agents;
using Urs.Plugin.Misc.Api.Models.Agents;
using Plugin.Api.Models.Agents;
using Urs.Services.Agents;
using Urs.Services.Localization;
using Urs.Services.Media;
using Urs.Services.Orders;
using Urs.Services.Stores;
using Urs.Services.Users;
using Plugin.Api.Models.User;
using Plugin.Api.Models.Catalog;

namespace Urs.Plugin.Api.Controllers
{
    /// <summary>
    /// 分销代理
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/agents")]
    [ApiAuthorize]
    [ApiController]
    public class AgentController : BaseApiController
    {
        private readonly IPictureService _pictureService;
        private readonly IUserService _userService;
        private readonly IOrderService _orderService;
        private readonly IAgentService _agentService;
        private readonly ILocalizationService _localizationService;

        public AgentController(IPictureService pictureService,
            IUserService customerService,
            IOrderService orderService,
            IAgentService agentService,
            ILocalizationService localizationService)
        {
            this._pictureService = pictureService;
            this._userService = customerService;
            this._orderService = orderService;
            this._agentService = agentService;
            this._localizationService = localizationService;
        }

        /// <summary>
        /// 代理升级，点击合作代理时调用
        /// 如非代理需要给予提示正在升级为代理
        /// 升级成功然后进入代理界面；
        /// </summary>
        /// <returns></returns>
        [HttpGet("upgrade")]
        public async Task<ApiResponse> Upgrade()
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<UpgradeInfo>.Warn("用户不存在或被禁用");

            if (string.IsNullOrWhiteSpace(user.PhoneNumber))
                return ApiResponse.Warn("手机不能为空");

            var isAgents = user.IsAgents();
            if (!isAgents)
            {
                var agentRole = _userService.GetUserRoleBySystemName(SystemRoleNames.Agents);
                if (agentRole == null)
                    throw new UrsException("'Agents' role could not be loaded");

                var regRole = user.UserRoles.FirstOrDefault(cr => cr.SystemName == SystemRoleNames.Agents);
                if (regRole == null)
                    user.UserRoleMappings.Add(new UserRoleMapping { UserRole = agentRole });

                user.Approved = true;
                _userService.UpdateUser(user);

                return ApiResponse.Success();
            }
            return ApiResponse.Success();
        }


        /// <summary>
        /// 我的分销信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("myinfo")]
        public async Task<ApiResponse<MyAgentInfo>> MyInfo()
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<MyAgentInfo>.Warn("用户不存在或被禁用");

            var data = await Task.Run(() =>
            {
                var model = new MyAgentInfo()
                {
                    Nickname = user.Nickname,
                    Realname = user.Realname,
                    Code = user.Code,
                    Approved = user.Approved,
                    Phone = user.PhoneNumber,
                    ImgUrl = _pictureService.GetPictureUrl(user.AvatarPictureId),
                    QRCode = _pictureService.GetPictureUrl(user.AvatarPictureId)
                };
                model.AvailAmount = _agentService.GetFees(user.Id, true, true) + _agentService.GetParentFees(user.Id, true, true);
                model.FreezingAmount = _agentService.GetFees(user.Id, false, true) + _agentService.GetParentFees(user.Id, false, true);
                model.MyOrderCount = _orderService.GetOrdersByAffiliateId(user.Id, pageSize: 1).TotalCount;
                model.MyUserCount = _userService.GetInvitations(user.Id, 0, 1).TotalCount;
                model.MyBonusAmount = _agentService.GetFees(user.Id, false, true) + _agentService.GetParentFees(user.Id, false, true);
                model.MyBonusCount = _agentService.GetCount(user.Id);
                return model;
            });
            return ApiResponse<MyAgentInfo>.Success(data);
        }
        /// <summary>
        /// 补充分销信息
        /// </summary>
        /// <returns></returns>
        [HttpPost("postinfo")]
        public async Task<ApiResponse> PostInfo(MoPostInfo moPostInfo)
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<MyAgentInfo>.Warn("用户不存在或被禁用");

            user.Realname = moPostInfo.RealName;
            if (!string.IsNullOrWhiteSpace(moPostInfo.Phone))
                user.PhoneNumber = moPostInfo.Phone;

            user.Approved = true;
            _userService.UpdateUser(user);

            return ApiResponse.Success();
        }

        /// <summary>
        /// 销售分红
        /// </summary>
        /// <returns></returns>
        [HttpGet("mysummary")]
        public async Task<ApiResponse<MoBonusSummary>> MyBonusSummary()
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<MoBonusSummary>.Warn("用户不存在或被禁用");

            var model = new MoBonusSummary();

            model.TotalAmount = _agentService.GetFees(user.Id, null, true) + _agentService.GetParentFees(user.Id, null, true);
            model.RealName = user.Realname;
            model.AvailAmount = _agentService.GetFees(user.Id, false, true) + _agentService.GetParentFees(user.Id, false, true);
            model.FreezingAmount = _agentService.GetFees(user.Id, false, true) + _agentService.GetParentFees(user.Id, false, true);
            model.NoValidAmount = _agentService.GetFees(user.Id, null, false) + _agentService.GetParentFees(user.Id, null, false);
            model.CashAmount = _agentService.GetFees(user.Id, true, true) + _agentService.GetParentFees(user.Id, true, true);
            return ApiResponse<MoBonusSummary>.Success(model);
        }

        /// <summary>
        /// 我的分销用户 
        /// </summary>
        /// <param name="page">页码（默认：1）</param>
        /// <param name="size">页大小（默认值：12）</param>
        /// <returns></returns>
        [HttpGet("myusers")]
        public async Task<ApiResponse<MoInvitees>> Users(int page = 1, int size = 12)
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<MoInvitees>.Warn("用户不存在或被禁用");

            var data = await Task.Run(() =>
            {
                var model = new MoInvitees();
                var command = new MoPagingFiltering
                {
                    PageNumber = page,
                    PageSize = size > 0 ? size : 10
                };

                var invitees = _userService.GetInvitations(user.Id, command.PageNumber - 1, command.PageSize);
                model.Paging.Page = command.PageNumber;
                model.Paging.Size = command.PageSize;
                model.Paging.TotalPage = invitees.TotalPages;
                foreach (var item in invitees)
                {
                    model.Items.Add(new MoInvitees.MoInvitee()
                    {
                        ImgUrl = item.GetAvatarUrl(),
                        Nickname = item.Nickname,
                        Phone = item.PhoneNumber,
                        Time = item.CreateTime
                    });
                }
                return model;
            });

            return ApiResponse<MoInvitees>.Success(data);
        }

        /// <summary>
        /// 我的分销订单
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet("myorders")]
        public async Task<ApiResponse<MoAgentOrder>> Orders(int page = 1, int size = 12)
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<MoAgentOrder>.Warn("用户不存在或被禁用");

            var data = await Task.Run(() =>
            {
                var model = new MoAgentOrder();
                var command = new MoPagingFiltering
                {
                    PageNumber = page,
                    PageSize = size > 0 ? size : 10
                };

                var orders = _orderService.GetOrdersByAffiliateId(user.Id, pageIndex: command.PageNumber - 1, pageSize: command.PageSize);
                model.Paging.Page = command.PageNumber;
                model.Paging.Size = command.PageSize;
                model.Paging.TotalPage = orders.TotalPages;
                foreach (var item in orders)
                {
                    var c = item.User;
                    model.Items.Add(new MoAgentOrder.MoOrderItem()
                    {
                        CustomerId = c.Id,
                        Nickname = c?.Nickname,
                        AvatarUrl = _pictureService.GetPictureUrl(c?.AvatarPictureId ?? 0, showDefaultPicture: true),
                        OrderId = item.Id,
                        OrderCode = item.Code,
                        OrderStatusId = item.OrderStatusId,
                        OrderStatus = item.OrderStatus.GetLocalizedEnum(_localizationService),
                        OrderTotal = PriceFormatter.FormatPrice(item.OrderTotal),
                        Remark = item.Remark,
                        CreatedTime = item.CreateTime
                    });
                }
                return model;
            });

            return ApiResponse<MoAgentOrder>.Success(data);
        }
        /// <summary>
        /// 我的分红明细
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet("mybonus")]
        public async Task<ApiResponse<MoAgentBonus>> MyBonusItems(int page = 1, int size = 12)
        {
            var user = RegisterUser;
            if (user == null || !user.Active || user.Deleted)
                return ApiResponse<MoAgentBonus>.Warn("用户不存在或被禁用");

            var data = await Task.Run(() =>
            {
                var model = new MoAgentBonus();
                var command = new MoPagingFiltering
                {
                    PageNumber = page,
                    PageSize = size > 0 ? size : 10
                };

                var agents = _agentService.GetList(user.Id, user.Id, pageIndex: command.PageNumber - 1, pageSize: command.PageSize);
                model.Paging.Page = command.PageNumber;
                model.Paging.Size = command.PageSize;
                model.Paging.TotalPage = agents.TotalPages;
                foreach (var item in agents)
                {
                    var c = _userService.GetUserById(item.UserId);
                    if (c == null) continue;
                    var order = _orderService.GetOrderById(item.OrderId);
                    if (order == null) continue;
                    model.Items.Add(new MoAgentBonus.MoBonusItem()
                    {
                        OrderId = item.Id,
                        OrderCode = order.Code,
                        OrderTotal = PriceFormatter.FormatPrice(order.OrderTotal),
                        UserId = c.Id,
                        Nickname = c.Nickname,
                        AvatarUrl = _pictureService.GetPictureUrl(c.AvatarPictureId),
                        Fee = item.AgentId == user.Id ? PriceFormatter.FormatPrice(item.Fee) : PriceFormatter.FormatPrice(item.ParentFee),
                        Remark = item.AgentId == user.Id ? "一级分红" : "二级分红",
                        Cash = item.Cash,
                        CreatedTime = item.CreateTime
                    });
                }
                return model;
            });

            return ApiResponse<MoAgentBonus>.Success(data);
        }
    }
}
